package dao;

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.InputStream;
import java.sql.Connection;
import java.util.Properties;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;

public class DBUtil {

    static{
        try {
            Class.forName("com.mysql.jdbc.Driver");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 获得连接
     * @return
     * @throws Exception
     */
    public static Connection getCon() throws Exception{
//        jdbc:mysql://localhost:3306/sh_books?useUnicode=true&characterEncoding=UTF-8
        String nameOfDatabase = "fanfan";
        String url="jdbc:mysql://localhost:3306/" + nameOfDatabase + "?useUnicode=true&characterEncoding=UTF-8";
        String user = "root";
        String password = "root";
        Connection con= DriverManager.getConnection(url,"root","root");
        return con;
    }

    /**
     * 执行增删改
     * @param sql
     * @param args
     * @throws Exception
     */
    public static int update(String sql,Object... args) throws Exception{
        Connection con=getCon();
        PreparedStatement pst=con.prepareStatement(sql);
        for(int i=0;i<args.length;i++){
            pst.setObject(i+1,args[i]);
        }
        int r=pst.executeUpdate();
        con.close();
        return r;
    }

    /**
     * 执行查询
     * @param sql
     * @param args
     * @return
     * @throws Exception
     */
    public static ResultSet query( String sql, Object... args) throws Exception{
        Connection con = getCon();
        PreparedStatement pst=con.prepareStatement(sql);
        for(int i=0;i<args.length;i++){
            pst.setObject(i+1,args[i]);
        }
        ResultSet rs=pst.executeQuery();
        return rs;
    }
}
